package com.ljpz.cart.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ljpz.cart.bean.Item;
import com.ljpz.cart.pojo.Cart;
import com.ljpz.common.utils.CookieUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by liujunchen on 2017/1/10.
 */
@Service
public class CartCookieService {
    private   static  final  String COOKIE_NAME="TT_CART";
    private   static  final  Integer  COOKIE_TIME=60*60*24*30*12;
    private  static   final ObjectMapper MAPPER= new ObjectMapper();
    @Autowired
    private  ItemService itemservice ;
    /**添加商品到购物车
     *
     *
     * 逻辑：判断加入的商品在原有购物车中是否存在，如果存在数量相加， 如果不存在，直接写入即可
     *
     *
     * @param itemId
     * @param request
     * @param response
     */

    public void addItemToCart   (Long itemId, HttpServletRequest request, HttpServletResponse response) throws  Exception {
        List<Cart> carts=this.queryCartlist(request);
        Cart cart = null;
        for (Cart c : carts){
            if (c.getItemId().longValue()==itemId.longValue()){
                //该商品已经存在购物车中
                cart = c ;
                break;
            }
        }
        if (null==cart ){
            //不存在
            cart=new Cart();
            cart.setCreated(new Date());
            cart.setUpdated(cart.getCreated());
            //商品的基本数据需要通过后台系统查询
            Item item= this.itemservice.queryById(itemId);
            cart.setItemId(itemId);
            cart.setItemTitle(item.getTitle());
            cart.setItemPrice(item.getPrice());
            cart.setItemImage(StringUtils.split(item.getImage(),",")[0]);
            cart.setNum(1);//TODO
            //商品加入购物车列表中
            carts.add(cart);
        }else {
            //存在
            cart.setNum(cart.getNum()+1);//TODO
            cart.setUpdated(new Date());
        }
        //将购物车列表数据写入到Cookie中去
        CookieUtils.setCookie(request,
                response,COOKIE_NAME,MAPPER.writeValueAsString(carts),COOKIE_TIME,true);

    }

    public List<Cart> queryCartlist(HttpServletRequest request) throws  Exception {
        String jsonData = CookieUtils.getCookieValue(request,COOKIE_NAME,true)  ;
        List<Cart> carts =null ;
        if(StringUtils.isEmpty(jsonData)){
            carts=new ArrayList<Cart>() ;
        }else {
            //反序列化
            carts=MAPPER.readValue(jsonData,
                    MAPPER.getTypeFactory().constructCollectionType(List.class,Cart.class));
        }
        //TODO  排序

        return  carts;
    }

    public void updateNum(Long itemId, Integer num, HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Cart> carts= this.queryCartlist(request) ;
        Cart cart = null;
        for (Cart c:carts){
            if (c.getItemId().longValue()==itemId.longValue()){
                //该商品已经存在购物车中
                cart=c ;
                break;
            }
        }
        if (cart!=null){
            cart.setNum(num);
            cart.setUpdated(new Date());
        }else
        {
            //参数非法
            return;
        }
        //将购物车列表数据写入到cookie中
        CookieUtils.setCookie(request,
                response,COOKIE_NAME,MAPPER.writeValueAsString(carts),COOKIE_TIME,true);

    }

    public void delete(Long itemId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Cart>carts=this.queryCartlist(request);
        Cart cart = null ;
        for (Cart c : carts){
            if (c.getItemId().longValue()==itemId.longValue()){
                cart=   c;
                carts.remove(c);
                break;
            }

        }
        if (cart==null){
            return   ;
        }
        //将购物车列表数据写入到cookie中
        CookieUtils.setCookie(request,
                response,COOKIE_NAME,MAPPER.writeValueAsString(carts),COOKIE_TIME,true);
    }


    /**
     * 完成购物车功能
     *
     *介绍cookie的记录内容只对应记录
     *
     * 新增addItemToCart_change01
     *
     * 新增queryCartlist_change01
     *
     *
     */
    public   List<Cart>queryCartlist_change01 (HttpServletRequest request) throws
            Exception{
        String jsonData= CookieUtils.getCookieValue(request,COOKIE_NAME,true)  ;
        List<Cart> carts   = null;
        if(StringUtils.isEmpty(jsonData)){
            carts=new ArrayList<Cart>()    ;
        }
        else
        {
            //反序列化
            carts =MAPPER.readValue(jsonData,
                    MAPPER.getTypeFactory().constructCollectionType(List.class,Cart.class));
        }
        Item item  =  new Item();
        //遍历carts补充完全购物车信息
        for(int  i=0 ; i<carts.size();i++) {
            item = this.itemservice.queryById(carts.get(i).getItemId());
            carts.get(i).setItemImage(item.getImage());
            carts.get(i).setItemPrice(item.getPrice());
            carts.get(i).setItemTitle(item.getTitle());
        }
        return   carts  ;

    }

    public  void addItemToCart_change01 (Long itemId ,Integer itemNum , HttpServletRequest request, HttpServletResponse response)
                                        throws  Exception{
        List<Cart> carts = this.queryCartlist_change01(request) ;
        Cart cart =  null;
        for(Cart c : carts){
            if (c.getItemId().longValue()==itemId.longValue()){
                //该商品已经存在购物车中
                cart= c ;
                break;
            }
        }
        if (null==cart ){
            //在购物车中不存在
            cart= new Cart();
            cart.setCreated(new Date());
            cart.setUpdated(new Date());
            cart.setItemId(itemId);
            cart.setNum(itemNum);
            //将商品加入购物车中
            carts.add(cart);
        }else {
            //存在数量累加
            cart.setNum(cart.getNum()+itemNum );
            cart.setUpdated(new Date());
        }
        //把对应的信息写入cookie中去
        CookieUtils.setCookie(request,response,COOKIE_NAME,MAPPER.writeValueAsString(carts),
                                COOKIE_TIME,true);
    }
}
